<!-- eslint-disable vue/valid-v-for -->
<template>
	<div>
		<el-input v-model="content" @keyup="handleInput(content)" placeholder="请输入中文" />
		<hr />
		<div class="pinyin-display">
			<ruby v-for="(item, index) in charactersList" :key="index">
				{{ item }}
				<rp>(</rp>
				<rt>{{ getPinyin(index) || "" }}</rt>
				<rp>)</rp>
			</ruby>
		</div>
	</div>
</template>
<script setup>
import { ref } from "vue";
import { pinyin } from "pinyin-pro";

const content = ref("");
/** 文字列表 */
const charactersList = ref([]);
/** 拼音列表 */
const PinyinList = ref([]);
// const reg = /[\u4e00-\u9fa5]/;

/** 获取拼音 */
function getPinyin(index) {
	if (Array.isArray(PinyinList.value) && index >= 0 && index < PinyinList.value.length) {
		return PinyinList.value[index];
	}
	return "";
}

/** 处理输入 */
function handleInput(char) {
	console.log(char);
	if (!char.trim()) {
		charactersList.value = [];
		PinyinList.value = [];
		return;
	}

	const chars = [...char];
	charactersList.value = chars;
	const res = pinyin(char, {
		type: "array"
	});

	if (res.length !== chars.length) {
		console.warn("拼音结果长度与字符长度不一致:", res, chars);
		// 手动为每个字符生成拼音
		const safePinyin = chars.map(c => pinyin(c, { type: "array", nonZh: "removed" })[0] || c);
		PinyinList.value = safePinyin;
	} else {
		PinyinList.value = res;
	}

	// return reg.test(char);
}
// 初始示例
handleInput("汉语拼音");
</script>

<style scoped>
.pinyin-display {
	font-size: 24px;
	line-height: 2;
}

ruby {
	margin-right: 1em;
}
</style>
<!-- https://github.com/zh-lx/pinyin-pro -->
